package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.mapper.SecKillGoodMapper;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISecKillGoodsService;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RocketMQMessageListener(
        consumerGroup = MQConstans.CREATE_ORDER_DELAY_GROUP,
        topic = MQConstans.SECKILL_ORDER_TOPIC,
        selectorExpression = MQConstans.CREATE_ORDER_DELAY_TAG
)
public class OrderSuccessDelayMQListener implements RocketMQListener<Map> {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private ISecKillGoodsService secKillGoodsService;

    @Autowired
    private SecKillGoodMapper secKillGoodMapper;


    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @Override
    public void onMessage(Map message) {

        System.out.println("订单下成功 到延时   等待支付的过程");

        Object seckillId = message.get("seckillId");
        String orderNo = (String) message.get("data");
        Long goodId = null;
        if (seckillId instanceof Long) {
            goodId = (Long) seckillId;
        } else if (seckillId instanceof Integer) {
            goodId = ((Integer) seckillId).longValue();
        }


        //改变订单的状态
        int count = orderInfoService.changeOrderInfoStatus(orderNo , OrderInfo.STATUS_TIMEOUT);

        if (count != 0 ){  //没有修改成功 改成功 回补库存     回补预存
            secKillGoodMapper.incrCount(goodId);


            secKillGoodsService.syncPreCount(goodId);

            //本地标识拦截
            rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_BROAD_DEST,goodId);

        }



    }
}
